System.Array.FindIndex 方法 (T[], Predicate)

方法描述

搜索与指定谓词定义的条件匹配的元素,然后返回整个 Array 中第一个匹配项的从零开始的索引。

语法定义(C# System.Array.FindIndex 方法 (T[], Predicate) 的用法)

public static int FindIndex(
	T[] array,
	Predicate match
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
array T[] 要搜索的从零开始的一维 Array。
match System-Predicate Predicate ,定义要搜索的元素的条件。
返回值 System.Int32 如果找到与 match 定义的条件相匹配的第一个元素,则为该元素的从零开始的索引;否则为 -1。

提示和注释

从 Array 的第一个元素开始向前搜索,到最后一个元素停止搜索。

Predicate 是对方法的委托,如果传递给它的对象与委托中定义的条件匹配,则该方法返回 true。 array 的元素被逐个传递给 Predicate

此方法的运算复杂度为 O(n),其中 n 是 array 的 Length。

System.Array.FindIndex 方法 (T[], Predicate)例子

该方法重载返回 –1,因为在该范围内没有以“saurus”结尾的恐龙名称。

using System;

public class Example
{
    public static void Main()
    {
        string[] dinosaurs = { "Compsognathus", 
            "Amargasaurus",   "Oviraptor",      "Velociraptor", 
            "Deinonychus",    "Dilophosaurus",  "Gallimimus", 
            "Triceratops" };

        Console.WriteLine();
        foreach(string dinosaur in dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine(
            "\nArray.FindIndex(dinosaurs, EndsWithSaurus): {0}", 
            Array.FindIndex(dinosaurs, EndsWithSaurus));

        Console.WriteLine(
            "\nArray.FindIndex(dinosaurs, 2, EndsWithSaurus): {0}",
            Array.FindIndex(dinosaurs, 2, EndsWithSaurus));

        Console.WriteLine(
            "\nArray.FindIndex(dinosaurs, 2, 3, EndsWithSaurus): {0}",
            Array.FindIndex(dinosaurs, 2, 3, EndsWithSaurus));
    }

    // Search predicate returns true if a string ends in "saurus".
    private static bool EndsWithSaurus(String s)
    {
        if ((s.Length > 5) && 
            (s.Substring(s.Length - 6).ToLower() == "saurus"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

/* This code example produces the following output:

Compsognathus
Amargasaurus
Oviraptor
Velociraptor
Deinonychus
Dilophosaurus
Gallimimus
Triceratops

Array.FindIndex(dinosaurs, EndsWithSaurus): 1

Array.FindIndex(dinosaurs, 2, EndsWithSaurus): 5

Array.FindIndex(dinosaurs, 2, 3, EndsWithSaurus): -1
 */

异常

异常 异常描述
ArgumentNullException
  • array 为 null。
  • match 为 null。

命名空间

namespace: System

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。